package test19.reader_;

import org.testng.annotations.Test;

import java.io.FileReader;
import java.io.IOException;

public class FileReader_ {
    public static void main(String[] args) {
    }
    //单个字符读取文件
    @Test
    public void readFile01(){
        String filePath = "D:\\story.txt";
        FileReader fileReader = null;

        try {
            fileReader = new FileReader(filePath);
            int data = 0;
           //循环读取 使用read, 单个字符读取
            while ((data = fileReader.read()) != -1){
                System.out.print((char)data);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                fileReader.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    //字符数组读取文件
    @Test
    public void readFile02(){
        String filePath = "D:\\story.txt";
        FileReader fileReader = null;

        try {
            fileReader = new FileReader(filePath);
            char[] buf = new char[8];
            int readlen = 0;
            //循环读取 使用read(buf), 返回的是实际读取到的字符数
            //如果返回-1, 说明到文件结束
            while ((readlen = fileReader.read(buf)) != -1){
                System.out.print(new String(buf,0,readlen));
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                fileReader.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
